#include "json.h"

namespace json
{
	value _Parse(const char * & i)
	{
		value output;
		
		while (*i != '\0')
		{
			if (*i == '{')	//Object
			{
				while (*i != '}')
				{
					value key = _Parse(++i);
					while (*i != ':'
						&& *i != '\0') ++i;
					value data = _Parse(++i);
					while (*i != ','
						&& *i != '}'
						&& *i != '\0') ++i;
					output.add((str)key, data);
				}
				return output;
			}
			else if (*i == '[')	//Array
			{
				while (*i != ']')
				{
					value data = _Parse(++i);
					while (*i != ','
						&& *i != ']'
						&& *i != '\0') ++i;
					output.add(data);
				}
				return output;
			}
			else if (*i == '"')	//String
			{
				++i;
				str s;
				while (*i != '"' && *i != '\0')	
				{
					s += *i;
					++i;
				}
				if (*i != '\0')
				{
					++i;
					output = s;
				}
				return output;
			}
			else if (*i == '-' 
				|| (*i >= '0' && *i <= '9'))	//Number
			{
				str s;
				while (*i != ' ' 
					&& *i != ','
					&& *i != '}'
					&& *i != ']'
					&& *i != '\0')	
				{
					s += *i;
					++i;
				}
				float f = (float)atof(s.c_str());
				output = f;
				return output;
			}
			else  //True, False, Null
			{
				str s;
				while (*i != ' ' 
					&& *i != ','
					&& *i != '}'
					&& *i != ']'
					&& *i != '\0')	
				{
					s += *i;
					++i;
				}

				for (unsigned int j = 0; j < s.length(); ++j) 
				{
					s[j] = toupper(s[j]);
				}
				
				if (s.compare("TRUE") == 0) 
				{
					output = true;
					return output;
				}
				else if (s.compare("FALSE") == 0) 
				{
					output = false;
					return output;
				}
				else if (s.compare("NULL") == 0)
				{
					return output;
				}
				else ;
			}

			++i;
		}

		return output;
	}

	str Compose(value & a)
	{
		str output;

		if (a.isObject())
		{
			output += "{";
			if (a.count() > 0)
			{
				output += a.keyAt(0);
				output += ":";
				output += Compose(a[0]);
				for (int i = 1; i < a.count(); ++i)
				{
					output += a.keyAt(i);
					output += ":";
					output += Compose(a[i]);
				}
			}
			output += "}";
			return output;
		}
		else if (a.isArray())
		{
			output += "[";
			if (a.count() > 0)
			{
				output += Compose(a[0]);
				for (int i = 1; i < a.count(); ++i)
				{
					output += ",";
					output += Compose(a[i]);
				}
			}
			output += " ]";
			return output;
		}
		else if (a.isString())
		{
			output += "\"";
			output += (str)a;
			output += "\"";
		}
		else if (a.isNumber())
		{
			char buffer[100];
			int l = sprintf(buffer, "%g", (float)a);
			for (int i = 0; i < l; ++i)
			{
				output += buffer[i];
			}
		}
		else if (a.isBoolean())
		{
			if ((bool)a)
			{
				output += "true";
			}
			else
			{
				output += "false";
			}
		}

		return output;
	}

	str ConvertUniCodes(const str & a)
	{
		return str();
	}
}